//
//  AppDelegate.m
//  ZQLearn
//
//  Created by admin on 2019/4/11.
//  Copyright © 2019 admin. All rights reserved.
//
#import "WXApi.h"
#import "AppDelegate.h"
#import "AFToast.h"
#import "ZRootViewController.h"
#import "ZIntroductionViewController.h"
#import "AppDelegate+NetworkMonitor.h"
#import "ZLoginViewController.h"
//#import "AvoidCrash.h"
#import "UIViewController+Swizzled.h"
@interface AppDelegate ()<WXApiDelegate>

@property (nonatomic,copy)NSString *access_token;
@property (nonatomic,copy)NSString *openid;

@end

@implementation AppDelegate

- (void)setMainWindow{
    
//    if (![[NSUserDefaults standardUserDefaults] boolForKey:LaunchKEY]) {
//        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:LaunchKEY];
//        ZIntroductionViewController *intro = [[ZIntroductionViewController alloc]init];
//        self.window.rootViewController = intro;
//    }else{
//        ZRootViewController * tabbarVC = [[ZRootViewController alloc] init];
//        self.window.rootViewController = tabbarVC;
//    }
    NSString *userId = [[NSUserDefaults standardUserDefaults] objectForKey:kUserId];
    NSString *integral = [[NSUserDefaults standardUserDefaults] objectForKey:@"integral"];
    [UserInfoSave shareInstance].nickName = [[NSUserDefaults standardUserDefaults] objectForKey:@"nickName"];
    [UserInfoSave shareInstance].integral = integral;
    [UserInfoSave shareInstance].uid = userId;
    if (userId.length<5) {
        
        ZLoginViewController *log = [[ZLoginViewController alloc]initWithNibName:@"ZLoginViewController" bundle:nil];
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:log];
        self.window.rootViewController = nav;
//        ZIntroductionViewController *intro = [[ZIntroductionViewController alloc]init];
//        self.window.rootViewController = intro;
    }else{
        
        ZRootViewController * tabbarVC = [[ZRootViewController alloc] init];
        self.window.rootViewController = tabbarVC;
    }
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    //    NRootViewController * tabbarVC = [[NRootViewController alloc] init];
    //    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:tabbarVC];
    //    self.window.rootViewController = tabbarVC;
    //    [[UIApplication sharedApplication]setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
    //微信APP注册
    [WXApi registerApp:@"wxaa44b1dbd49b1038"];
    
//    [AvoidCrash makeAllEffective];
    
    [self networkMonitor];
    [self setMainWindow];
//    ZRootViewController * tabbarVC = [[ZRootViewController alloc] init];
//    self.window.rootViewController = tabbarVC;
    [self.window makeKeyAndVisible];
    
    
    //    //加入容错处理，并且接受信息
//    [AvoidCrash becomeEffective];
//    //注册监听，获取AvoidCrash捕获的崩溃日志的详细信息
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealWithCrashMessage:)  name:AvoidCrashNotification object:nil];
    
    //////
    UN_SWIZZ_IT
    
    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark - 分享支付回调
///这个方法是iOS9之后的方法 因为现在iOS12了，之后只用着一个就好了
-(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    if ([options[UIApplicationOpenURLOptionsSourceApplicationKey] isEqualToString:@"com.tencent.xin"]){
        
        //微信 支付 分享，登录
        ///***********注意登录可能y是一个新的字段标记*******************************
        if ([url.host containsString:@"pay"]) {
            ////微信支付
            return [WXApi handleOpenURL:url delegate:self];
            
        }else{
            ///分享
            return [WXApi handleOpenURL:url delegate:self];
            
        }
        
    }else{
        //qq 如果平台太多的话，可以参考WTShare中的写法分享样板工程中的写法
        //         return [TencentOAuth HandleOpenURL:url];
//        return [QQApiInterface handleOpenURL:url delegate:self];
        return YES;
    }
}

////基本上腾讯的分享，登录，支付在这个代理里面可以处理完 ，然后支付宝用的自己的代理
///这个方法微信和qq 分享的回调可以共用，需要在里面判断一下就好了
// 从微信/qq分享过后点击返回应用的时候调用
- (void)onResp:(BaseResp *)resp {
    
    ////1.微信分享
    
    //把返回的类型转换成与发送时相对于的返回类型,这里为SendMessageToWXResp
    if([resp isKindOfClass:[SendMessageToWXResp class]]){
        
        SendMessageToWXResp *sendResp = (SendMessageToWXResp *)resp;
        if (sendResp.errCode==0) {
            [AFToast showText:@"分享成功"];
        }else{
             [AFToast showText:@"分享失败"];
        }
        //使用UIAlertView 显示回调信息
//        NSString *str = [NSString stringWithFormat:@"%d",sendResp.errCode];
//        UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"回调信息" message:str delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
//        [alertview show];
    }
    /*  WXSuccess           = 0,    /**< 成功    */
    //    WXErrCodeCommon     = -1,   /**< 普通错误类型    */
    //    WXErrCodeUserCancel = -2,   /**< 用户点击取消并返回    */
    //    WXErrCodeSentFail   = -3,   /**< 发送失败    */
    //    WXErrCodeAuthDeny   = -4,   /**< 授权失败    */
    //    WXErrCodeUnsupport  = -5,   /**< 微信不支持    */
    //    */
    
    ////2.qq分享
    ////**************
//    else if ([resp isKindOfClass:[SendMessageToQQResp class]] && resp.type == ESENDMESSAGETOQQRESPTYPE)
//    {
//        SendMessageToQQResp* sendReq = (SendMessageToQQResp*)resp;
//        // sendReq.result->0分享成功 -4取消分享
//        if ([sendReq.result integerValue] == 0) {
//            NSLog(@"qq share success");
//        }else{
//            NSLog(@"qq share failed");
//        }
//    }
    
    ////3.微信登录
    ///////*********微信登录*******************
    else if([resp isKindOfClass:[SendAuthResp class]]){//判断是否为授权登录类
        SendAuthResp *req = (SendAuthResp *)resp;
        if([req.state isEqualToString:@"wx_oauth_authorization_state"]){//微信授权成功
            ///这个code作用要通过请求拿到Access_token
            NSLog(@"%@",req.code); //获得code
            ///这个code每次是不一样的，是唯一的
            //021gCAW71uqbrM1oIoV719oFW71gCAWW
//            [self getWXTokenWithCode:req.code];
            [self getWXTokenWithCode:req.code para:@{}];
            
        }
        
    }else{
        ///微信支付
        if([resp isKindOfClass:[PayResp class]]){//支付
            
            PayResp *req = (PayResp *)resp;
            if(req.errCode == 0){
                //支付成功
                YYLog(@"微信支付成功");
                [AFToast showText:@"支付成功"];
                
            }else{
                //支付失败  req.errStr 支付失败原因
                if (req.errCode==-2) {
                     [AFToast showText:@"支付取消"];
                }else{
                    [AFToast showText:req.errStr?:@"支付失败"];
                    YYLog(@"微信支付失败");
                }
                
            }
        }
        
    }
}


#pragma mark - 微信登录相关操作
///通过授权 code 拿下面的请求
///https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code


////通过token 获取用户个人信息
///https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID
#define kWXGetTokenUrl @"https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code"


///根据req.code 获取 access_token和openid
- (void)getWXTokenWithCode:(NSString *)code  para:(NSDictionary *)para{
    
    NSString *url = @"https://api.weixin.qq.com/sns/oauth2/access_token";
    NSDictionary *dict = @{@"appid":kWXAppID,@"secret":kWXAppSecret,@"code":code,@"grant_type":@"authorization_code",};
    [self getTokeAndOpenidWithUrl:url para:dict];
}
//access_token = "21_j9mbYxXEtcyhG8Pj-t605X3w_U1LS8kX7lmOFWECJRzR8UQGwvpXuLGNRaFNo_v4soz0iNG5r_dSxZTwvx5hlmlMuSsaX8Hf6wP1zHWdGm0",
//openid = "ox32_51q1yAAKO9TdL2WCaI5-UkU",
- (void)getTokeAndOpenidWithUrl:(NSString *)url para:(NSDictionary *)para{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/javascript",@"application/json",@"text/html", nil];
    manager.requestSerializer.timeoutInterval = 10;
    AFSecurityPolicy * securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    //    如果是需要验证自建证书，需要设置为YES
    securityPolicy.allowInvalidCertificates = YES;
    securityPolicy.validatesDomainName = NO;
    manager.securityPolicy = securityPolicy;
    [manager GET:url parameters:para progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable result) {
        YYLog(@"%@",result);
        self.access_token = result[@"access_token"];
        self.openid = result[@"openid"];
        NSDictionary *dic = @{@"access_token":self.access_token,@"openid":self.openid,};
        WeakStament(ws);
        [ws getUserInfoWithPara:dic];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        YYLog(@"%@",error);
    }];
}
///根据access_token 和 openid 获取用户信息
-(void)getUserInfoWithPara:(NSDictionary *)para{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/javascript",@"application/json",@"text/html", nil];
    manager.requestSerializer.timeoutInterval = 10;
    AFSecurityPolicy * securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    //    如果是需要验证自建证书，需要设置为YES
    securityPolicy.allowInvalidCertificates = YES;
    securityPolicy.validatesDomainName = NO;
    manager.securityPolicy = securityPolicy;
    [manager GET:@"https://api.weixin.qq.com/sns/userinfo" parameters:para progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable result) {
        
        YYLog(@"%@",result);
///微信登录成功后返回头像，昵称和openid(这个在上个接口就返回了，这里又返回了一次)
        //调用自己的登录接口
        //这里应该发个通知到登录页面，然后在登录页面调用微信登录接口
        [[NSNotificationCenter defaultCenter]postNotificationName:kWXLoginNoti object:result];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        YYLog(@"%@",error);
    }];
    
}

/*
{
    openid = "ox32_51q1yAAKO9TdL2WCaI5-UkU",
    city = "Xinxiang",
    country = "CN",
    nickname = "绮鑫",
    privilege =     (
    ),
    language = "zh_CN",
    headimgurl = "http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTKhEoBNAojSZNqoMI4EM5pKRBBuO8vjUpsr62VvA371SZM1j64U6dLDs9bheffviaNFaSGT6nwnChA/132",
    unionid = "oRWxF5zRdJLkEX6MHBpqjcBHW2FQ",
    sex = 1,
    province = "Henan",
}


*/



@end
